from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from util.permission import SuperAdminPermission
from django.contrib.auth.hashers import make_password, check_password
from . import serializers
from . import models
from util.token import create_token
from util import throttle
from django.core.cache import cache
# Create your views here.

class TestLogAPIView(APIView):
    def get(self,request):
        1/0
        return Response({'code':'1223'})
    def post(self,request):
        sss
        return Response({'code':222})

class TestCache(APIView):
    authentication_classes = []
    def get(self,request):
        operation = request.query_params.get('name')
        if operation=='set':
            cache.set('list',['lhz','zzh','yf'])
            cache.set('dict', {'name':'lhz','age':56})
            return Response({'code':200})
        else:
            ret1 = cache.get('list')
            ret2 = cache.get('dict')
            print(ret1,type(ret1))
            print(ret2, type(ret2))
            return Response({'code':200,'list':ret1,'dict':ret2})


class LoginView(APIView):
    authentication_classes = []
    def post(self,request):
        username = request.data.get('username')
        password = request.data.get('password')
        user = models.UserModel.objects.filter(username=username).first()

        is_true = check_password(password,user.password)
        if is_true:
            token = create_token(user.pk)
            response = Response({'code':200,"msg":'登录成功'})
            response.set_cookie('token',token)
            return response
        else:
            return Response({'code':400,'msg':'用户名或密码错误'})

class RegisterView(APIView):
    permission_classes = [SuperAdminPermission]
    def get(self,request):
        return Response({'code':100})
    def post(self,request):
        username = request.data.get('username')
        name = request.data.get('name')
        phoneNumber = request.data.get('phoneNumber')
        role = request.data.get('role')
        password = phoneNumber.strip()[-8:]
        password = make_password(password)
        data = {
            'username':username,
            'realName':name,
            'phoneNumber':phoneNumber,
            'role':role,
            'password':password
        }
        ser = serializers.UserLoginModelSerializer(data=data, context={'request': request})
        if ser.is_valid():
            ser.save()
            return Response({'code': 200, 'msg':ser.data})
        else:
            return Response({'code':400,'msg':ser.errors})


class HomeView(APIView):
    throttle_classes = [throttle.UserNameThrottle]
    def get(self,request):
        return Response({'code':200,'msg':'一分钟只能访问一次'})

